<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单详情</title>
    <link rel="stylesheet" href="/scriptZIP/indexPlus.css">
    <style scoped>
        body {
            margin: 20px;
            font-family: Arial, sans-serif;
        }

        h2,
        h3 {
            margin: 10px 0;
        }

        .el-card {
            margin-bottom: 20px;
            padding: 15px;
        }

        .el-table {
            margin-top: 10px;
        }

        .el-row {
            margin-bottom: 20px;
        }

        .el-row:last-child {
            margin-bottom: 0;
        }

        .full-width-table {
            width: 100%;
        }

        [v-cloak] {
            display: none;
        }

        .back-button {
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div id="orderDetailsApp" v-cloak>
        <el-container>
            <el-header>
                <h2>订单详情</h2>
            </el-header>
            <el-main>
                <!-- 返回按钮 -->
                <el-button class="back-button" @click="goBack" type="primary">返回</el-button>

                <!-- 基本信息 -->
                <el-card>
                    <h3>基本信息</h3>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="订单类型">
                                <span>{{ order.way === 7 ? "线上" : "线下" }}</span>
                            </el-form-item>
                            <el-form-item label="订单号">
                                <span>{{ order.tradeNo }}</span>
                            </el-form-item>
                            <el-form-item label="订单建立时间">
                                <span>{{ order.time }}</span>
                            </el-form-item>
                            <el-form-item label="类型">
                                <span>{{ order.orderType === 1 
      ? "新签" 
      : order.orderType === 2 
        ? "续费" 
        : order.orderType === 3 
          ? "新签尾款" 
          : "未知类型" }}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="校区名称">
                                <span>{{ order.schoolName }}</span>
                            </el-form-item>
                            <el-form-item label="学员姓名">
                                <span>{{ order.studentName }}</span>
                            </el-form-item>
                            <el-form-item label="联系电话">
                                <span>{{ order.bindCode }}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 课程详情 -->
                <el-card>
                    <h3>课程详情</h3>
                    <el-table :data="order.courseDetailsList" border class="full-width-table">
                        <el-table-column prop="courseName" label="课程名称" width="200">
                            <template #default="scope">
                                <span>{{ scope.row.courseName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="quantity" label="数量" width="200">
                            <template #default="scope">
                                <el-input-number 
                                    v-model="scope.row.quantity" 
                                    :min="0.01" 
                                    :step="0.01" 
                                    :precision="2" 
                                    @change="handleQuantityChange(scope.row)" 
                                    placeholder="数量">
                                </el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column prop="coursePrice" label="总价 (元)" width="200">
                            <template #default="scope">
                                <span>{{ (scope.row.coursePrice / 100).toFixed(2) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" label="实收 (元)" width="200">
                            <template #default="scope">
                                <el-input-number 
                                    v-model="scope.row.amountInYuan" 
                                    :step="0.01" 
                                    :min="0" 
                                    placeholder="实收"
                                    @change="handleAmountChange(scope.row)">
                                </el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column prop="msType" label="报读模式" width="100">
                            <template #default="scope">
                                <span>{{ getMsTypeLabel(scope.row.msType) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="startTime" label="开课时间" width="230">
                            <template #default="scope">
                                <el-date-picker v-model="scope.row.startTime" type="date" placeholder="选择开课时间" format="YYYY-MM-DD" 
                                value-format="YYYY-MM-DD"></el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column prop="endTime" label="课程有效期至" width="230">
                            <template #default="scope">
                                <el-date-picker v-model="scope.row.endTime" type="date" placeholder="选择结束时间" format="YYYY-MM-DD" 
                                value-format="YYYY-MM-DD"></el-date-picker>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
                
                <!-- 修改经办信息 -->
                <el-card>
                    <h3>经办信息</h3>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="经办人">
                                <span>{{ order.handleUser }}</span>
                            </el-form-item>
                            <el-form-item label="业绩归属人">
                                <el-select v-model="order.performance" placeholder="请选择业绩归属人" filterable clearable>
                                    <el-option
                                        v-for="user in staffUsers"
                                        :key="user.id"
                                        :label="user.name"
                                        :value="user.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="收款日期">
                                <el-date-picker v-model="order.handlingDate" type="date" placeholder="选择收款日期" format="YYYY-MM-DD" 
                                value-format="YYYY-MM-DD"></el-date-picker>
                            </el-form-item>
                            <el-form-item label="备注信息">
                                <el-input type="textarea" v-model="order.remark" placeholder="请输入备注信息"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                
                <!-- 提交按钮 -->
                <el-button type="primary" @click="submitOrder">提交</el-button>
                
            </el-main>
        </el-container>
    </div>

    <script src="/scriptZIP/vue.global.js"></script>
    <script src="/scriptZIP/index.full.js"></script>
    <script src="/scriptZIP/axios.min.js"></script>
    <!-- plus中文包 -->
    <script src="/scriptZIP/zh-cn-plus.js"></script> 
    <script>
        const { createApp } = Vue;
        var agentId = localStorage.getItem('agentId')
        createApp({
    data() {
        return {
            order: {
                courseDetailsList: [],
                handleUser: "",
                performance: "",
                handlingDate: "",
                remark: "",
            },
            initialOrder: null, // 保存初始状态
            staffUsers: [],
        };
    },
    created() {
        const id = this.getParams().id;
        axios.get(`/pc/order/orderDetails/${id}`).then(response => {
            this.order = response.data;

            // 初始化数据并转换金额
            this.order.courseDetailsList.forEach(course => {
                course.originalQuantity = course.quantity;
                course.originalPrice = course.coursePrice;
                course.amountInYuan = (course.amount || 0) / 100; // 分转元
            });

            // 保存初始状态
            this.initialOrder = JSON.parse(JSON.stringify(this.order));
        });
        axios.get('/pc/staffUser/all/' + agentId).then(function (res) {
                this.staffUsers = res.data;
            }.bind(this));
    },
    methods: {
        handleQuantityChange(row) {
            if (row.quantity <= 0) {
                this.$message.error("数量必须大于 0");
                row.quantity = 0.01; // 默认值
                return;
            }

            const fixedPrice = row.originalPrice / row.originalQuantity;
            row.coursePrice = Math.round(row.quantity * fixedPrice); // 更新总价（以分为单位）
        },
        handleAmountChange(row) {
            row.amount = Math.round(row.amountInYuan * 100); // 元转分
        },
        datejisuan(startDate, endDate) {
                let start = new Date(startDate);
                let end = new Date(endDate);
                let count = 0;
                // 循环遍历日期范围
                while (start <= end) {
                    // 获取当前日期是星期几 (0: Sunday, 1: Monday, ..., 6: Saturday)
                    let dayOfWeek = start.getDay();
                    // 如果是工作日 (1-5 代表周一到周五)
                    if (dayOfWeek >= 1 && dayOfWeek <= 5) {
                        count++;
                    }
                    // 将日期增加一天
                    start.setDate(start.getDate() + 1);
                }

                return count;
            },
            submitOrder() {
    const promises = [];
    const id = this.getParams().id;

    let totalAmount = 0; // 总价
    let totalReceived = 0; // 实收

    // 遍历课程详情，检查每个字段的变化
    this.order.courseDetailsList.forEach(course => {
        const initialCourse = this.initialOrder.courseDetailsList.find(c => c.id === course.id);
        const changedFields = {};
        if (Number(course.quantity) !== Number(initialCourse?.quantity)) {
    changedFields.quantity = course.quantity;
}

        if (course.coursePrice !== initialCourse?.coursePrice) {
            changedFields.coursePrice = course.coursePrice;
        }
        if (course.amount !== initialCourse?.amount) {
            changedFields.amount = course.amount;
        }
        if (course.startTime !== initialCourse?.startTime) {
            changedFields.startTime = course.startTime;
            changedFields.countNum = [1, 3, 6, 7].includes(course.msType)
                ? course.quantity
                : this.datejisuan(course.startTime, course.endTime);
        }
        if (course.endTime !== initialCourse?.endTime) {
            changedFields.endTime = course.endTime;
            changedFields.countNum = [1, 3, 6, 7].includes(course.msType)
                ? course.quantity
                : this.datejisuan(course.startTime, course.endTime);
        }

        // 如果有变化的字段，则加入请求队列
        if (Object.keys(changedFields).length > 0) {
            promises.push(axios.post(`/pc/order/updateCourseDetail`, { id: course.id, ...changedFields }));
        }

        // 总价和实收计算
        totalAmount += course.coursePrice || 0;
        totalReceived += course.amount || 0;
    });

    // 检查订单信息的变化
    const orderChanges = {};
    if (this.order.performance !== this.initialOrder.performance) {
        orderChanges.performance = this.order.performance;
    }
    if (this.order.handlingDate !== this.initialOrder.handlingDate) {
        orderChanges.handlingDate = this.order.handlingDate;
    }
    if (this.order.remark !== this.initialOrder.remark) {
        orderChanges.remark = this.order.remark;
    }
    if (totalAmount !== this.initialOrder.totalAmount) {
        orderChanges.orderPrice = totalAmount;
    }
    if (totalReceived !== this.initialOrder.totalReceived) {
        orderChanges.fee = totalReceived;
    }

    // 如果有订单字段的变化，则发起请求
    if (Object.keys(orderChanges).length > 0) {
        promises.push(axios.post(`/pc/order/updateOrder`, { id, ...orderChanges }));
    }

    // 提交所有变化
    Promise.all(promises)
        .then(() => {
            this.$message.success("订单修改成功！");
        })
        .catch(error => {
            console.error("Error submitting order:", error);
            this.$message.error("提交失败，请重试！");
        });
},

        getParams() {
            // 获取 URL 参数
            const query = location.search.substring(1);
            const vars = query.split("&");
            const params = {};
            for (let i = 0; i < vars.length; i++) {
                const pair = vars[i].split("=");
                params[pair[0]] = decodeURIComponent(pair[1]);
            }
            return params;
        },
        getMsTypeLabel(msType) {
                    const modes = {
                        1: "按课时收费",
                        2: "按月收费",
                        3: "按天收费",
                        4: "按季收费",
                        5: "按期收费",
                        6: "按课包收费",
                        7: "按体验收费",
                    };
                    return modes[msType] || "未知模式";
                },
        goBack() {
            window.history.back();
        },
    },
}).use(ElementPlus,{locale: ElementPlusLocaleZhCn}).mount("#orderDetailsApp");
    </script>
</body>

</html>